package cn.imvc.app.models;



import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import cn.imvc.app.entities.Dealer;
import cn.imvc.app.entities.Domain;
import cn.imvc.app.entities.Member;
import cn.imvc.app.repositories.DomainRepository;
import cn.imvc.data.domain.ViewRequest;

@Service
public class DomainModelImpl implements DomainModel{
	
	@Autowired
	private DomainRepository domainRepository;

	@Autowired
	MemberModel memberModel;

	@Autowired
	DealerModel dealerModel;
	
	
	public Domain get(int id){
		return domainRepository.findOne(id);
	}
	
	
	public Page<Domain> find(ViewRequest viewRequest) {
		return (Page<Domain>) domainRepository.findAll();
	}

	public Domain save(Domain domain) {
		
		Domain domain2 = domainRepository.saveAndFlush(domain);
		
		
		return domain2;
	}
	public Domain update(Domain newDomain) {
		Domain loadDomain=get(newDomain.getId());
		BeanUtils.copyProperties(newDomain, loadDomain, new String[]{"id"});
		
		return domainRepository.saveAndFlush(loadDomain);
	}
	public void delete(int id) {
		domainRepository.delete(id);
		
	}
	public void deleteBatch(int[] ids) {

		for (int id : ids) {
			delete(id);
		}
		
	}
	
	public Domain findBymemberId(Integer memberId){
		return domainRepository.findByMemberId(memberId);
	}
	
	public List<Domain> getByDomain(String domain) {
		return domainRepository.getByDomain(domain);
	}

	public Map<String, String> updateDomain(Member member, String domain) {
		Map<String, String> result = new HashMap<String, String>();
		result.put("code", "0");
		if (member == null) {
			result.put("code", "-1");
			result.put("msg", "请登录");
			return result;
		}
		List<Domain> list = getByDomain(domain);
		if(list == null || (list != null && list.size() == 0)){
			Domain entity = findBymemberId(member.getId());
			if(entity.getDomain().equals(domain)){
				result.put("msg", "新域名与老域名相同");
			} else {
				entity.setDomain(domain);
				save(entity);
				// dealer表也有domain字段
				Dealer dealer = dealerModel.findByMember(member);
				// 会员一定有域名，但不一定是分销商
				if(dealer != null){
					dealer.setDomain(domain);
					dealer.setUpdatedAt(new Date());
					dealerModel.save(dealer);
				}
				result.put("code", "1");
				result.put("msg", "修改成功");
			}
		} else {
			result.put("msg", "域名已存在");
		}
		return result;
	}

}
